use crossterm::{
    style::{Color, Stylize, PrintStyledContent},
    cursor, queue,
    QueueableCommand
};
use std::io;

pub struct Renderer;

impl Renderer {
    pub fn begin_frame(stdout: &mut io::Stdout) -> io::Result<()> {
        queue!(stdout, cursor::MoveTo(0, 0))
    }
    
    pub fn draw_text(
        stdout: &mut io::Stdout,
        text: &str,
        x: u16,
        y: u16,
        fg: Color,
        bg: Color,
    ) -> io::Result<()> {
        let styled_text = text.with(fg).on(bg);
        queue!(
            stdout,
            cursor::MoveTo(x, y),
            PrintStyledContent(styled_text),
        )
    }

    pub fn draw_box(
        stdout: &mut io::Stdout,
        x: u16,
        y: u16,
        width: u16,
        height: u16,
        fg: Color,
        bg: Color,
    ) -> io::Result<()> {
        // 绘制顶部和底部边框
        for i in x..x + width {
            // 顶部边框
            let top_char = if i == x {
                "┌"
            } else if i == x + width - 1 {
                "┐"
            } else {
                "─"
            };
            queue!(
                stdout,
                cursor::MoveTo(i, y),
                PrintStyledContent(top_char.with(fg).on(bg)),
            )?;

            // 底部边框
            let bottom_char = if i == x {
                "└"
            } else if i == x + width - 1 {
                "┘"
            } else {
                "─"
            };
            queue!(
                stdout,
                cursor::MoveTo(i, y + height - 1),
                PrintStyledContent(bottom_char.with(fg).on(bg)),
            )?;
        }

        // 绘制左右边框
        for j in y + 1..y + height - 1 {
            // 左边框
            queue!(
                stdout,
                cursor::MoveTo(x, j),
                PrintStyledContent("│".with(fg).on(bg)),
            )?;

            // 右边框
            queue!(
                stdout,
                cursor::MoveTo(x + width - 1, j),
                PrintStyledContent("│".with(fg).on(bg)),
            )?;
        }

        Ok(())
    }

    pub fn parse_color(color_str: &str) -> Color {
        match color_str.to_lowercase().as_str() {
            "black" => Color::Black,
            "white" => Color::White,
            "red" => Color::Red,
            "green" => Color::Green,
            "blue" => Color::Blue,
            "yellow" => Color::Yellow,
            "magenta" => Color::Magenta,
            "cyan" => Color::Cyan,
            _ => Color::White,
        }
    }
    
    pub fn end_frame(stdout: &mut io::Stdout) -> io::Result<()> {
        queue!(stdout, cursor::Hide)
    }
}